/**   
 * @Title: RechargeUninBinding.java 
 * @Package com.esun.elk.ui.views.userinfo.recharge 
 * @Description: 银联充值页
 * @author Billy Qigs@500wan.com   
 * @date 2011-11-01 上午11:11:11  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.mylotteryact.recharg;

import java.net.URLEncoder;
import java.text.DecimalFormat;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.rabbit2.communicaters.recharg.ZhiFuBaoOrderIDCommunicater;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.zhifubao.AlixId;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.zhifubao.BaseHelper;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.zhifubao.MobileSecurePayHelper;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.zhifubao.MobileSecurePayer;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.zhifubao.PartnerConfig;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.zhifubao.ResultChecker;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.zhifubao.Rsa;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: RechargeZhiFuBao
 * @Description: (支付宝充值界面)
 * @author: Billy Qigs@500wan.com
 * @date: 2011-11-1 下午12:06:12
 * 
 */
public class RechargeZhiFuBao extends Activity implements android.view.View.OnClickListener {

	private Button btnSubmit;
	private ImageButton btnBack;
	private EditText etMoney;

	private String money = "";
	private String callBackURL = "";

	private ZhiFuBaoOrderIDCommunicater orderIDCommunicater;
	private Handler rechargeHandler;
	private ProgressDialog progress;
	private ProgressDialog progressOrder;

	private static final int GET_ORDERID_SUCCEED = 10100;
	private static final int GET_ORDERID_FAILED = 10101;
	private static final String SUBJET = "支付宝充值";
	private static final String BODY = "支付宝充值";
	private static final String SIGN_TYPE = "RSA";
	private static final String CHAR_SET = "utf-8";
	private static final String ORDER_ID = "orderid";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.recharge_zhifubao_act);

		initUI();
		initHandler();
	}

	private void initUI() {

		progress = new ProgressDialog(RechargeZhiFuBao.this);
		progressOrder = ViewerUtil.showProgressDialog(RechargeZhiFuBao.this, "获取单号...");
		orderIDCommunicater = new ZhiFuBaoOrderIDCommunicater();

		// check to see if the MobileSecurePay is already installed.
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		mspHelper.detectMobile_sp();

		btnSubmit = (Button) findViewById(R.id.recharge_zfb_btn_submit);
		btnSubmit.setOnClickListener(this);

		btnBack = (ImageButton) findViewById(R.id.recharge_zfb_btn_goBack);
		btnBack.setOnClickListener(this);

		etMoney = (EditText) findViewById(R.id.recharge_zfb_edt_num);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.recharge_zfb_btn_goBack:

			RechargeZhiFuBao.this.finish();

			break;

		case R.id.recharge_zfb_btn_submit:

			EDebug.o(this, "点击提交");
			money = etMoney.getText().toString();
			EDebug.o(this, "money = " + money);
			if (money != null && money.length() > 0 && (Double.valueOf(money)) > 0) {
				DecimalFormat df = new DecimalFormat("0.00");
				Double dMoney = Double.valueOf(money);
				money = df.format(dMoney);
				EDebug.o(this, "money = " + money);
				// 检测是否安装支付宝支付服务
				MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
				boolean isMobile_spExist = mspHelper.detectMobile_sp();
				if (!isMobile_spExist) {
					EDebug.o(this, "没安装支付宝");
					return;
				}
				EDebug.o(this, "已经安装支付宝");
				// 获取单号
				progressOrder.show();
				getOrderID();

			} else {
				ViewerUtil.showTipDialog(RechargeZhiFuBao.this, "请输入正确金额", false);
			}

			break;
		}
	}

	// start pay for this order.
	private void payTheOrder(String orderID) {
		try {
			// prepare the order info.

			EDebug.o(this, "准备支付参数信息");
			String orderInfo = getOrderInfo(orderID);
			String signType = getSignType();
			EDebug.o(this, signType);
			String strsign = sign(signType, orderInfo);
			strsign = URLEncoder.encode(strsign);
			String info = orderInfo + "&sign=" + "\"" + strsign + "\"" + "&" + getSignType();
			EDebug.o(this, "orderInfo = " + info);
			// start the pay.
			MobileSecurePayer msp = new MobileSecurePayer();
			EDebug.o(this, "开始支付");
			boolean bRet = msp.pay(info, rechargeHandler, AlixId.RQF_PAY, RechargeZhiFuBao.this);

			if (bRet) {
				// show the progress bar to indicate that we have started paying.
				closeProgress();
				progress = BaseHelper.showProgress(this, null, "正在支付", false, true);
			} else {

			}
		} catch (Exception ex) {
			Toast.makeText(RechargeZhiFuBao.this, R.string.remote_call_failed, Toast.LENGTH_SHORT).show();
		}
	}

	// 获取单号线程 get the out_trade_no for an order.
	private void getOrderID() {

		new Thread() {

			@Override
			public void run() {
				super.run();
				EDebug.o(this, "获取订单号");
				Message msg = new Message();

				try {

					if (orderIDCommunicater.isGetOrderIDSucceed(RechargeZhiFuBao.this, money)) {
						msg = rechargeHandler.obtainMessage(GET_ORDERID_SUCCEED, orderIDCommunicater.getResult().get(ORDER_ID));
					} else {
						msg = rechargeHandler.obtainMessage(GET_ORDERID_FAILED, null);
					}
					rechargeHandler.sendMessage(msg);
				} catch (Exception e) {
					msg = rechargeHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					rechargeHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	private void initHandler() {
		rechargeHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				try {

					switch (msg.what) {

					case GET_ORDERID_SUCCEED:
						progressOrder.dismiss();
						String strOrderID = (String) msg.obj;
						EDebug.o(this, "获取订单号成功 order id = " + strOrderID);
						callBackURL = orderIDCommunicater.getResult().get(Key.KEY_CALLBACKURL);
						payTheOrder(strOrderID);

						break;

					case GET_ORDERID_FAILED:
						progressOrder.dismiss();
						Toast.makeText(RechargeZhiFuBao.this, "单号获取失败", Toast.LENGTH_SHORT).show();

						break;

					case AlixId.RQF_PAY:
						String strRet = (String) msg.obj;
						closeProgress();
						EDebug.o(this, "支付结果" + strRet);
						try {

							String memo = "memo=";
							int imemoStart = strRet.indexOf("memo=");
							imemoStart += memo.length();
							int imemoEnd = strRet.indexOf(";result=");
							memo = strRet.substring(imemoStart, imemoEnd);
							EDebug.o(this, "memo = " + memo);
							int resultStatusStart = strRet.indexOf("resultStatus={");
							resultStatusStart = resultStatusStart + "resultStatus={".length();
							int resultStatusEnd = strRet.indexOf("};memo=");
							String resultStatus = strRet.substring(resultStatusStart, resultStatusEnd);
							ResultChecker resultChecker = new ResultChecker(strRet);
							EDebug.o(this, "result status = " + resultStatus);
							if (resultStatus.equals("9000")) {
								memo = "{交易成功}";
							}
							int retVal = resultChecker.checkSign();
							if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
								BaseHelper.showDialog(RechargeZhiFuBao.this, "提示", getResources().getString(R.string.check_sign_failed), android.R.drawable.ic_dialog_alert);
							} else {
								BaseHelper.showDialog(RechargeZhiFuBao.this, "提示", memo, R.drawable.infoicon);
							}

						} catch (Exception e) {
							e.printStackTrace();

							BaseHelper.showDialog(RechargeZhiFuBao.this, "提示", strRet, R.drawable.infoicon);
						}
						break;

					case Config.CONNECTION_FAIL:

						progressOrder.dismiss();

						// ViewerUtil.showTipDialog(RechargeZhiFuBao.this, Language.STR_CONNECTIONFAIL, false);
						Toast.makeText(RechargeZhiFuBao.this, Language.STR_CONNECTIONFAIL.toString(), Toast.LENGTH_SHORT).show();
						break;

					default:

						break;

					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				closeProgress();
			}

		};
	}

	// close the progress bar
	void closeProgress() {
		try {
			if (progress != null) {
				progress.dismiss();
				progress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// get the selected order info for pay.
	String getOrderInfo(String orderID) {
		String strOrderInfo = "partner=" + "\"" + PartnerConfig.PARTNER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "seller=" + "\"" + PartnerConfig.SELLER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "out_trade_no=" + "\"" + orderID + "\"";
		strOrderInfo += "&";
		strOrderInfo += "subject=" + "\"" + SUBJET + "\"";
		strOrderInfo += "&";
		strOrderInfo += "body=" + "\"" + BODY + "\"";
		strOrderInfo += "&";
		strOrderInfo += "total_fee=" + "\"" + money + "\"";
		strOrderInfo += "&";
		strOrderInfo += "notify_url=" + "\"" + callBackURL + "\"";

		return strOrderInfo;
	}

	// sign the order info.
	String sign(String signType, String content) {
		return Rsa.sign(content, PartnerConfig.RSA_PRIVATE);
	}

	//
	// get the sign type we use.
	String getSignType() {
		String getSignType = "sign_type=" + "\"" + SIGN_TYPE + "\"";
		return getSignType;
	}

	//
	// get the char set we use.
	String getCharset() {
		String charset = "charset=" + "\"" + CHAR_SET + "\"";
		return charset;
	}

	// the OnCancelListener for lephone platform.
	public static class AlixOnCancelListener implements DialogInterface.OnCancelListener {
		Activity mcontext;

		public AlixOnCancelListener(Activity context) {
			mcontext = context;
		}

		public void onCancel(DialogInterface dialog) {
			mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		try {
			progress.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
